/**
 * 放大镜构造函数
 * @param el 初始化的video或者img元素
 * @param scale 放大倍率
 * @param width 放大框宽度
 * @param height 放大框高度
 */
class MagnifyingGlass {
  constructor({ el, scale = 1, width = 150, height = 150 }) {
    this.width = width;
    this.height = height;
    this.scale = scale;
    this.valueDiv = null;
    this.offSetX = 0;
    this.offSetY = 0;
    this.moveFlag = true;
    this.originalEle =
      typeof el === "string" ? document.getElementById(el) : el;
    this.div = null;
    this.img = null;
    this.canvas = null;
    this.originalScale = 1;
  }
  init() {
    this.img = document.createElement("img");
    this.div = document.createElement("div");
    this.div.style.position = "absolute";
    this.div.style.width = this.width + "px";
    this.div.style.height = this.height + "px";
    this.div.style.zIndex = "99999";
    this.div.style.display = "none";
    this.div.style.overflow = "hidden";
    this.img.style.width = "100%";
    this.img.style.height = "100%";
    this.div.style.background = "rgba(0,0,0,0.7)";
    this.div.style.border = "1px solid #aaa";
    this.div.appendChild(this.img);
    document.body.appendChild(this.div);
    const _this = this;
    this.originalEle.onmouseleave = function() {
      _this.div.style.display = "none";
    };
    this.originalScale =
      this.originalEle.naturalWidth / this.originalEle.offsetWidth;
  }
  /** 生成图片 */
  generateImage() {
    this.canvas = this.canvas || document.createElement("canvas");
    this.canvas.width = this.width;
    this.canvas.height = this.height;
    const sx = this.offSetX * this.originalScale - this.width / 2;
    const sy = this.offSetY * this.originalScale - this.height / 2;
    this.canvas
      .getContext("2d")
      .drawImage(
        this.originalEle,
        sx,
        sy,
        this.width,
        this.height,
        0,
        0,
        this.width,
        this.height
      );
    const imgData = this.canvas.toDataURL("images/jpge");
    this.img.src = imgData;
    this.img.style.transform = `scale(${this.scale})`;
    this.moveFlag = true;
  }
  registerMouse() {
    const _this = this;
    this.originalEle.onmousemove = function(ev) {
      if (!_this.moveFlag) return;
      _this.moveFlag = false;
      _this.div.style.left = ev.clientX + 10 + "px";
      _this.div.style.top =
        ev.clientY - _this.originalEle.offsetHeight / 2 + "px";
      _this.offSetX = ev.offsetX;
      _this.offSetY = ev.offsetY;
      _this.div.style.display = "block";
      _this.generateImage();
    };
  }
  start() {
    this.init();
    this.registerMouse();
    const _this = this;
    window.onbeforeunload = function() {
      _this.stop();
    };
  }
  stop() {
    this.img.style.display = "none";
    this.div.style.display = "none";
    this.div.onmouseenter = null;
    this.originalEle.onmousemove = null;
    this.canvas = null;
    document.body.removeChild(this.div);
  }
}
export default MagnifyingGlass;
